package com.chhuang.utils.file;

import java.io.File;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.chhuang.utils.Assert;
import com.chhuang.utils.string.AES256Encryption;

/**
 * AES256加密解密文件工具类
 * @author 黄晨
 * @date 2013-5-10
 *
 */
public class AESFileUtil {
	static Log log = LogFactory.getLog(AESFileUtil.class);
	
	/**
	 * 将传入文件按照AES256解密，返回字节数据
	 * @param srcFileAbsPath 原路径名
	 * @return
	 * @throws Exception 
	 */
	public static byte[] decryptFile(String srcFileAbsPath) throws Exception {
		if(Assert.isInvalidString(srcFileAbsPath)) {
			log.debug("参数无效。");
			return null;
		}
		
		File srcFile = new File(srcFileAbsPath);
		
		if(!srcFile.exists()) {
			throw new IOException("源文件不存在。");
		}
		
		//加密字节码
		byte[] decryptBytes = ByteFileUtil.readFileByBytes(srcFileAbsPath);
		
		if(decryptBytes == null || decryptBytes.length == 0) {
			throw new IOException("加密字节码为空。");
		}
		
		return AES256Encryption.decrypt(decryptBytes);
	}
	
	/**
	 * 将文件加密生成加密后的文件
	 * @param srcFileAbsPath 待加密文件
	 * @param destPath 加密后的路径
	 * @return
	 * @throws Exception
	 */
	public static String encryptFile(String srcFileAbsPath, String destPath) throws Exception {
		if(Assert.isInvalidString(srcFileAbsPath) || Assert.isInvalidString(destPath)) {
			log.debug("参数无效。");
			return null;
		}
		
		File srcFile = new File(srcFileAbsPath);
		
		if(!srcFile.exists()) {
			throw new IOException("源文件不存在。");
		}
		
		//加密字节码
		byte[] bytes = ByteFileUtil.readFileByBytes(srcFileAbsPath);
		
		if(bytes == null || bytes.length == 0) {
			throw new IOException("文件字节码为空。");
		}
		
		byte[] encryptBytes = AES256Encryption.encrypt(bytes);
		
		String filename = srcFile.getName();
		
		String absFilePath = FileUtil.createFile(destPath, filename, "");
		
		ByteFileUtil.writeBytesToFile(absFilePath, encryptBytes);
		
		return absFilePath;
	}
	
	/**
	 * 将文件加密生成加密后的文件
	 * @param srcFileAbsPath
	 * @return
	 * @throws Exception
	 */
	public static String encryptFile(String srcFileAbsPath) throws Exception {
		if(Assert.isInvalidString(srcFileAbsPath)) {
			log.debug("参数无效。");
			return null;
		}
		
		return encryptFile(new File(srcFileAbsPath));
	}
	
	/**
	 * 将文件加密生成加密后的文件
	 * @param srcFile
	 * @return
	 * @throws Exception
	 */
	public static String encryptFile(File srcFile) throws Exception {
		if(srcFile==null || !srcFile.exists()) {
			throw new IOException("源文件不存在。");
		}
		
		return encryptFile(srcFile.getPath(), srcFile.getParent());
	}
	
}
